<style>
  * {margin:0; padding:0;}
</style>
<canvas id="canvas"></canvas>
<script>
/*
  生成随机小球，半径/开始位置/颜色/运动速度 都随机
*/
function randomByRange(min, max) {
  return Math.random() * (max - min) + min
}
class Ball {
  static makeBall() {
    const {innerWidth, innerHeight} = window
    const r = randomByRange(5, 15)
    const x = randomByRange(r, innerWidth - r)
    const y = randomByRange(r, innerHeight - r)
    const color = `rgb(${
      randomByRange(0, 255)}, ${
      randomByRange(0, 255)}, ${
      randomByRange(0, 255)})`
    const dx = (Math.random()>0.5?1:-1) * randomByRange(1, 4)
    const dy = (Math.random()>0.5?1:-1) * randomByRange(1, 4)
    return new Ball(r, [x, y], color, [dx, dy])
  }
  constructor(r, [x, y], color, [dx, dy]) {
    this.r0 = r
    this.r = r
    this.x = x
    this.y = y
    this.color = color
    this.dx = dx
    this.dy = dy
  }
  move() {
    let {x, y} = this
    x += this.dx
    y += this.dy

    if (x<this.r) { // 撞左边界
      x = this.r
      this.dx = -this.dx
    }
    if (y<this.r) { // 撞上边界
      y = this.r
      this.dy = -this.dy
    }
    if (x>window.innerWidth - this.r) { // 撞右边界
      x = window.innerWidth - this.r
      this.dx = -this.dx
    }
    if (y>window.innerHeight - this.r) { // 撞下边界
      y = window.innerHeight - this.r
      this.dy = -this.dy
    }

    this.x = x
    this.y = y
  }
  toBig() {
    let r = this.r
    r += 1
    if (r > 100) { r = 100}
    this.r = r
  }
  toSmall() {
    let r = this.r
    r -= 1
    if (r < this.r0) { r = this.r0}
    this.r = r
  }
}

const canvas = document.getElementById('canvas')
canvas.style.background = 'yellow'
const c = canvas.getContext('2d')
let balls = []
let mx = 0
let my = 0

function resizeCanvas() {
  canvas.width = window.innerWidth
  canvas.height = window.innerHeight
}
function render() {
  // c.clearRect(0, 0, window.innerWidth, window.innerHeight)
  c.globalAlpha = 0.1
  balls.forEach((b) => {
    const len = Math.sqrt((b.x - mx)**2 + (b.y - my)**2)
    if (len < 50) {
      b.toBig()
    } else {
      b.toSmall()
    }
    c.fillStyle = b.color
    c.beginPath()
    c.arc(b.x, b.y, b.r, 0, Math.PI * 2)
    c.fill()
    b.move()
  })
}
window.onresize = () => {
  resizeCanvas()
  render()
}
function animation() {
  render()
  window.requestAnimationFrame(animation)
}
window.onload = () => {
  resizeCanvas()
  balls = [...Array(1000)].map(() => Ball.makeBall())
  render()
  window.requestAnimationFrame(animation)
}
window.onmousemove = (e) => {
  mx = e.x
  my = e.y
}


</script>